<template>
  <el-dialog
    v-model="state.show"
    title="能耗趋势"
    width="800px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div class="chart-container">
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import * as echarts from 'echarts'

const state = reactive({
  show: false,
  spaceId: null as string | number | null,
})

const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null

// 生成模拟数据
const generateMockData = (baseValue: number, count: number): number[] => {
  const data: number[] = []
  for (let i = 0; i < count; i++) {
    // 生成一个在基准值附近波动的随机值
    const value = baseValue + Math.random() * 100 - 50
    data.push(Math.max(0, Math.round(value)))
  }
  return data
}

// 生成时间轴数据
const generateTimeAxis = (): string[] => {
  const times: string[] = []
  for (let i = 0; i < 24; i++) {
    for (let j = 0; j < 4; j++) {
      times.push(
        `${i.toString().padStart(2, '0')}:${(j * 15).toString().padStart(2, '0')}`
      )
    }
  }
  return times
}

// 初始化图表
const initChart = () => {
  const chartDom = chartRef.value
  if (!chartDom) return
  
  chart = echarts.init(chartDom as HTMLElement)
  
  const timeData = generateTimeAxis()
  const todayData = generateMockData(100, 96) // 96个点（24小时 * 每小时4个点）
  const yesterdayData = generateMockData(120, 96)
  
  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      borderWidth: 0,
      textStyle: {
        color: '#666'
      },
      axisPointer: {
        type: 'cross',
        lineStyle: {
          color: '#ccc'
        }
      }
    },
    legend: {
      data: ['今日', '昨日']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeData,
      axisLabel: {
        interval: 11 // 每隔12个点（3小时）显示一个标签
      }
    },
    yAxis: {
      type: 'value',
      name: 'kW',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '今日',
        type: 'line',
        data: todayData,
        itemStyle: {
          color: '#36cfc9'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(54, 207, 201, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(54, 207, 201, 0)'
            }
          ])
        },
        smooth: true
      },
      {
        name: '昨日',
        type: 'line',
        data: yesterdayData,
        itemStyle: {
          color: '#a8a8a8'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(168, 168, 168, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(168, 168, 168, 0)'
            }
          ])
        },
        smooth: true
      }
    ]
  }
  
  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize()
}

// 打开弹窗的方法
const openDialog = (spaceId) => {
  console.log('spaceId', spaceId)
  
  state.spaceId = spaceId
  state.show = true
  nextTick(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })
}

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
})

defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
.chart-container {
  padding: 20px;
}
</style>